package com.uzhie.web.aop;

import com.alibaba.fastjson.JSONObject;
import com.uzhie.web.anno.Auth;
import com.uzhie.spring.HttpServletRequestWrapper;
import com.uzhie.web.module.User;
import com.uzhie.util.SessionManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by TangFei on 2018/8/15.
 * 认证拦截器
 */
public class AuthInterceptor implements HandlerInterceptor {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private SessionManager<User> sessionManager;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info("enter method preHandle");
        boolean flag = true;
        HttpServletRequestWrapper requestWrapper = (HttpServletRequestWrapper) httpServletRequest;
        JSONObject requestJSON = requestWrapper.getRequestJSON();
        if (o instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) o;
            boolean annotationPresent = handlerMethod.getMethod().isAnnotationPresent(Auth.class);
            if (annotationPresent) {
                boolean tokenRequired = handlerMethod.getMethod().getAnnotation(Auth.class).tokenRequired();
                if (tokenRequired) {
                    boolean validateToken = validateToken(requestJSON.getString("requestToken"));
//                    boolean validateToken = true;
                    if (validateToken) {
                        flag = true;
                    } else {
                        flag = false;
                        httpServletResponse.setStatus(401);
//                        throw new RuntimeException("token error!");
                    }
                } else {
                    flag = true;
                }
//                flag = tokenRequired ? validateToken(requestJSON.getString("requestToken")) : true;
            } else {
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        logger.info("enter method postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("enter method afterCompletion");
    }

    private boolean validateToken(String token) {
        logger.info("收到的 token 为：" + token);
        try {
            sessionManager.get(token);
            logger.info("token is OK!");
            return true;
        } catch (NoSuchFieldException e) {
            logger.error("token error!", e);
            return false;
        }
    }

}
